import React, { useState, useEffect, useContext } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import { BsEye, BsHeart, BsHeartFill, BsChat, BsBookmark, BsBookmarkFill, BsShare } from 'react-icons/bs';
import { FaEdit, FaTrashAlt } from 'react-icons/fa';
import { articleService, commentService } from '../services/api';
import { AuthContext } from '../contexts/AuthContext';
import Spinner from '../components/common/Spinner';
import CommentForm from '../components/comment/CommentForm';
import CommentList from '../components/comment/CommentList';

const ArticleDetail = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const { user } = useContext(AuthContext);
  
  const [article, setArticle] = useState(null);
  const [comments, setComments] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [isLiked, setIsLiked] = useState(false);
  const [isSaved, setIsSaved] = useState(false);

  useEffect(() => {
    const fetchArticleData = async () => {
      try {
        setLoading(true);
        
        // 获取文章详情
        const articleRes = await articleService.getArticleById(id);
        setArticle(articleRes.data);
        
        // 获取评论
        const commentsRes = await commentService.getCommentsByArticleId(id);
        setComments(commentsRes.data);
        
        // 检查用户是否已点赞和收藏该文章
        if (user) {
          const userActionsRes = await articleService.getUserArticleActions(id);
          setIsLiked(userActionsRes.data.liked);
          setIsSaved(userActionsRes.data.saved);
        }
        
        // 更新文章阅读量
        await articleService.incrementViewCount(id);
        
        setLoading(false);
      } catch (err) {
        console.error('加载文章详情失败', err);
        setError('加载文章详情失败，请稍后重试');
        setLoading(false);
      }
    };
    
    fetchArticleData();
  }, [id, user]);

  const handleLike = async () => {
    if (!user) {
      navigate('/login', { state: { from: `/articles/${id}` } });
      return;
    }
    
    try {
      await articleService.likeArticle(id);
      setIsLiked(!isLiked);
      setArticle(prev => ({
        ...prev,
        likes: isLiked ? prev.likes - 1 : prev.likes + 1
      }));
    } catch (err) {
      console.error('点赞失败', err);
    }
  };

  const handleSave = async () => {
    if (!user) {
      navigate('/login', { state: { from: `/articles/${id}` } });
      return;
    }
    
    try {
      await articleService.saveArticle(id);
      setIsSaved(!isSaved);
    } catch (err) {
      console.error('收藏失败', err);
    }
  };

  const handleShare = () => {
    navigator.clipboard.writeText(window.location.href);
    // 这里可以添加一个提示，表示链接已复制
  };

  const handleDelete = async () => {
    if (window.confirm('确定要删除这篇文章吗？此操作不可撤销。')) {
      try {
        await articleService.deleteArticle(id);
        navigate('/');
      } catch (err) {
        console.error('删除文章失败', err);
      }
    }
  };

  const handleCommentSubmit = async (commentData) => {
    try {
      const res = await commentService.createComment({
        ...commentData,
        articleId: id
      });
      
      setComments(prev => [res.data, ...prev]);
      return true;
    } catch (err) {
      console.error('提交评论失败', err);
      return false;
    }
  };

  // 格式化日期
  const formatDate = (dateString) => {
    const options = { year: 'numeric', month: 'long', day: 'numeric' };
    return new Date(dateString).toLocaleDateString('zh-CN', options);
  };

  if (loading) {
    return <Spinner />;
  }

  if (error) {
    return (
      <div className="container mx-auto px-4 py-10 text-center">
        <h2 className="text-2xl text-red-500 mb-4">{error}</h2>
        <button
          onClick={() => window.location.reload()}
          className="btn btn-primary"
        >
          重新加载
        </button>
      </div>
    );
  }

  if (!article) {
    return (
      <div className="container mx-auto px-4 py-10 text-center">
        <h2 className="text-2xl mb-4">文章不存在</h2>
        <Link to="/" className="btn btn-primary">
          返回首页
        </Link>
      </div>
    );
  }

  // 检查当前用户是否为文章作者
  const isAuthor = user && article.author.id === user.id;

  return (
    <div className="container mx-auto px-4 py-10">
      <div className="max-w-4xl mx-auto">
        {/* 文章头部 */}
        <header className="mb-8">
          <div className="flex flex-wrap gap-2 mb-4">
            {article.tags && article.tags.map(tag => (
              <Link
                key={tag.id}
                to={`/tags/${tag.id}`}
                className="inline-block text-xs bg-primary-100 dark:bg-primary-900 text-primary-800 dark:text-primary-200 px-2 py-1 rounded-full"
              >
                {tag.name}
              </Link>
            ))}
          </div>
          <h1 className="text-3xl md:text-4xl font-bold text-dark-800 dark:text-dark-200 mb-4">
            {article.title}
          </h1>
          
          {/* 作者信息和发布日期 */}
          <div className="flex items-center mb-6">
            <img
              src={article.author.avatar || 'https://via.placeholder.com/40'}
              alt={article.author.username}
              className="w-10 h-10 rounded-full mr-3"
            />
            <div>
              <Link
                to={`/authors/${article.author.id}`}
                className="font-medium text-dark-700 dark:text-dark-300 hover:text-primary-600 dark:hover:text-primary-400"
              >
                {article.author.username}
              </Link>
              <p className="text-sm text-dark-500 dark:text-dark-400">
                {formatDate(article.createdAt)}
                {article.updatedAt !== article.createdAt && 
                  ` · 更新于 ${formatDate(article.updatedAt)}`}
              </p>
            </div>
          </div>
          
          {/* 文章操作 */}
          <div className="flex flex-wrap justify-between items-center py-4 border-t border-b border-gray-200 dark:border-dark-700">
            <div className="flex items-center space-x-4 text-dark-600 dark:text-dark-300">
              <div className="flex items-center">
                <BsEye className="mr-1" />
                <span>{article.views} 阅读</span>
              </div>
              <button 
                onClick={handleLike}
                className={`flex items-center ${isLiked ? 'text-red-500' : ''}`}
              >
                {isLiked ? <BsHeartFill className="mr-1" /> : <BsHeart className="mr-1" />}
                <span>{article.likes} 赞</span>
              </button>
              <div className="flex items-center">
                <BsChat className="mr-1" />
                <span>{comments.length} 评论</span>
              </div>
            </div>
            
            <div className="flex items-center space-x-3">
              {isAuthor && (
                <>
                  <Link 
                    to={`/articles/edit/${id}`} 
                    className="text-blue-500 hover:text-blue-600"
                    title="编辑文章"
                  >
                    <FaEdit />
                  </Link>
                  <button
                    onClick={handleDelete}
                    className="text-red-500 hover:text-red-600"
                    title="删除文章"
                  >
                    <FaTrashAlt />
                  </button>
                </>
              )}
              <button
                onClick={handleSave}
                className={`${isSaved ? 'text-primary-600' : 'text-dark-500 dark:text-dark-400'}`}
                title={isSaved ? '取消收藏' : '收藏文章'}
              >
                {isSaved ? <BsBookmarkFill /> : <BsBookmark />}
              </button>
              <button
                onClick={handleShare}
                className="text-dark-500 dark:text-dark-400 hover:text-primary-600"
                title="分享文章"
              >
                <BsShare />
              </button>
            </div>
          </div>
        </header>
        
        {/* 文章内容 */}
        <div className="prose prose-lg dark:prose-invert max-w-none mb-10">
          <div dangerouslySetInnerHTML={{ __html: article.content }} />
        </div>
        
        {/* 文章分类 */}
        {article.category && (
          <div className="mb-10">
            <span className="text-dark-600 dark:text-dark-300">分类：</span>
            <Link
              to={`/categories/${article.category.id}`}
              className="text-primary-600 dark:text-primary-400 hover:underline"
            >
              {article.category.name}
            </Link>
          </div>
        )}
        
        {/* 评论部分 */}
        <section className="mt-10">
          <h2 className="text-2xl font-bold text-dark-800 dark:text-dark-200 mb-6">
            评论 ({comments.length})
          </h2>
          
          <CommentForm onSubmit={handleCommentSubmit} />
          
          {comments.length > 0 ? (
            <CommentList comments={comments} />
          ) : (
            <div className="text-center py-8 text-dark-500 dark:text-dark-400">
              暂无评论，成为第一个评论的人吧！
            </div>
          )}
        </section>
      </div>
    </div>
  );
};

export default ArticleDetail; 